import React, { useState } from "react";
import WujieReact from "wujie-react";
import { preloadApp } from "wujie";

const isDev = import.meta.env.DEV;

const subApps = {
  react: {
    name: "sub-react",
    url: isDev ? "http://localhost:5174/sub-react/" : "/sub-react/",
  },
  vue: {
    name: "sub-vue",
    url: isDev ? "http://localhost:5175/sub-vue/" : "/sub-vue/",
  },
};

export default function App() {
  const [active, setActive] = useState<"react" | "vue">("react");

  // 预加载子应用以提升切换速度
  React.useEffect(() => {
    preloadApp({ name: subApps.react.name, url: subApps.react.url });
    preloadApp({ name: subApps.vue.name, url: subApps.vue.url });
  }, []);

  return (
    <div style={{ fontFamily: "system-ui, sans-serif", padding: 16 }}>
      <h1>Wujie 主应用</h1>
      <nav style={{ display: "flex", gap: 8, marginBottom: 12 }}>
        <button
          onClick={() => setActive("react")}
          disabled={active === "react"}
        >
          打开 React 子应用
        </button>
        <button onClick={() => setActive("vue")} disabled={active === "vue"}>
          打开 Vue 子应用
        </button>
      </nav>

      <div style={{ border: "1px solid #ddd", borderRadius: 8, padding: 12 }}>
        {active === "react" ? (
          <WujieReact name={subApps.react.name} url={subApps.react.url} sync />
        ) : (
          <WujieReact name={subApps.vue.name} url={subApps.vue.url} sync />
        )}
      </div>
    </div>
  );
}
